package com.hzhc.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzhc.annotation.SysTemLog;
import com.hzhc.common.BaseController;
import com.hzhc.dto.RouterDto;
import com.hzhc.entity.SysUser;
import com.hzhc.entity.SysUserSecurity;
import com.hzhc.enumBean.LoginUserType;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.service.SysMenuService;
import com.hzhc.service.SysUserSecurityService;
import com.hzhc.service.SysUserService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.utils.StringUtils;
import com.hzhc.utils.TokenUtil;
import com.hzhc.vo.SysMenuVo;
import com.hzhc.vo.SysUserVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 登陆控制器
 * @author wxk
 * @since 2023年07月04日16:21:03
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("")
public class LoginController extends BaseController {

    private final SysMenuService menuService;

    private final SysUserService userService;

    private final SysUserSecurityService sysUserSecurityService;

    @Value("${webSocketUrl}")
    private String webSocketUrl;

    /**
     * 用户登陆
     * @param request
     * @param sysUser
     * @return ResultUtil<SysUserVo>
     */
    @PostMapping("/login")
    @SysTemLog(operModul = "用户登陆", operType = "用户登陆", operDesc = "用户登陆", modular = "PC")
    public ResultUtil<SysUserVo> login(HttpServletRequest request, @RequestBody SysUser sysUser){
        String loginname = sysUser.getLoginname();
        String password = sysUser.getPassword();
        if (StrUtil.isBlank(loginname)) {
            return ResultUtil.build( ResultUtilCodeEnum.ACCOUNT_ERROR);
        }
        if (StrUtil.isBlank(password)) {
            return ResultUtil.build( ResultUtilCodeEnum.PASSWORD_ERROR);
        }
        SysUserVo vo = userService.login(loginname, password);
        //处理 锁相关
        String msg=lockLogin(loginname, vo);
        if(StringUtils.isNotEmpty(msg)){
            List<SysUserSecurity> securities = sysUserSecurityService.getBaseMapper()
                    .selectList(new QueryWrapper<SysUserSecurity>().eq("status", 1).eq("disable",0));
            SysUserVo sysUserVo=new SysUserVo();
            if(msg.indexOf("账号已锁")!=-1){
                sysUserVo.setShowMsg("账号已锁定,"+securities.get(0).getPasswordLockTime()+"分钟后再试");
            }else if(msg.indexOf("剩余")!=-1){//表示待锁账号
                sysUserVo.setShowMsg("用户名密码错误"+securities.get(0).getPasswordErrorNum()+"次,账号锁定"+securities.get(0).getPasswordLockTime()+"分钟");
            }
            return  ResultUtil.build(sysUserVo,400,msg);
        }
        if(vo != null) {
            //获取用户所有角色
            String token = TokenUtil.sign(vo);
            vo.setToken(token);
            vo.setUserType(LoginUserType.USER.getCode());
            vo.setWebSocketUrl(webSocketUrl);
            //保存登录时间
            SysUser user = userService.getById(vo.getId());
            user.setLastLoginTime(LocalDateTime.now());
            userService.updateById(user);
        }else {
            return ResultUtil.build(ResultUtilCodeEnum.USER_PASSWORD_ERROR);
        }
        return ResultUtil.build(vo,ResultUtilCodeEnum.SUCCESS);
    }

    private String lockLogin(String loginname, SysUserVo vo) {
        if(vo != null){
            if(vo.getLoginTime()!=null && vo.getLoginTime().isAfter(LocalDateTime.now())){
                return "账号已锁!";
            }
            //登录成功 还原锁
            SysUser user = userService.getById(vo.getId());
            user.setLoginNum(0);
            user.setLoginTime(null);
            userService.updateById(user);
            return "";
        }else{
            //提示
            String msg=sysUserSecurityService.checkLoginFailure(loginname,"pc",null);
            return msg;
        }
    }

//    @PostMapping("/auth/refreshToken")
//    public String refreshToken(HttpServletRequest request, @RequestBody JSONObject obj) {
//        String token = obj.getString("refresh_token");
//        if (StrUtil.isNotBlank(token)) {
//            return TokenUtil.refreshToken(token,LoginUserType.USER.getCode());
//        }
//        return token;
//    }

    @PostMapping("/auth/refreshToken")
    public ResultUtil<String> refreshToken(HttpServletRequest request, @RequestBody JSONObject obj) {
        String token = obj.getString("refresh_token");
        if (StrUtil.isNotBlank(token)) {
            String newToken = TokenUtil.refreshToken(token, LoginUserType.USER.getCode());
            if( newToken== null){
                return ResultUtil.build(ResultUtilCodeEnum.TOKEN_ERROR);
            }else{
                return ResultUtil.build(newToken,ResultUtilCodeEnum.SUCCESS);
            }
        }
        return ResultUtil.build(ResultUtilCodeEnum.TOKEN_ERROR);
    }

    /**
     * 用户退出
     * @param request
     * @param response
     * @return ResultUtil<T>
     */
    @RequestMapping("/logout")
    @SysTemLog(operModul = "退出登录", operType = "退出", operDesc = "退出登录", modular = "PC")
    public ResultUtil<T> logout(HttpServletRequest request, HttpServletResponse response) {
        //删除用户的token数据
        SysUser user = new SysUser();
        user.setId( TokenUtil.getUserID(request));
        user.setSalt("");
        userService.updateById(user);
        return ResultUtil.build(ResultUtilCodeEnum.LOGIN_OUT_SUCCESS);
    }

    /**
     * 测试接口
     * @param request
     * @param response
     * @return ResultUtil<T>
     */
    @RequestMapping("/testToken")
    public ResultUtil<T> testToken(HttpServletRequest request, HttpServletResponse response) {
        return ResultUtil.ok();
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @PostMapping("/getRouters")
    public ResultUtil<List<RouterDto>> getRouters(HttpServletRequest request){
        Long userId = TokenUtil.getUserID(request);
        List<SysMenuVo> menus = menuService.selectMenuTreeByUserId(userId);
        return ResultUtil.build(menuService.buildMenus(menus), ResultUtilCodeEnum.SUCCESS);
    }

}
